/*
 * $Id: ExportDialog.java,v 1.3 2003/05/18 20:05:13 znamenacek Exp $
 *
 * Copyright (c) Milan Jedlicka
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

package net.sf.vofce.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileFilter;

import java.io.File;

import java.util.*;
import java.util.ResourceBundle;

import net.sf.vofce.export.*;

/**
 * Export dialog (template list, template descriptions) setting up export
 * properties.
 *
 * @author Milan Jedlicka
 */
class ExportDialog extends JDialog implements ListSelectionListener {

	/** Localised resource strings. */
        private static ResourceBundle resources;
	
	/** Manager of export templates */
	protected TemplateManager templates = new TemplateManager();

	/** Exporter of images (= graphs) */
	protected ImageExporter ie = new ImageExporter();

	/** Graph setting dialog */
	protected GraphDialog graphDialog = new GraphDialog(this, ie);
	
	// GUI parts
	
	protected JList list;

	protected JList tempList;
    	private JLabel tempAvail;
    	private JButton ok;
    	private JLabel tempDesc;
    	private JPanel buttons;
    	private JButton cancel;
    	private JTextArea descTextArea;
    	private JPanel tempDescription;
    	private JPanel exportPanel;
	private JButton graphSizeButton;	
	private JScrollPane scrollPane;

	/** Default constructor */
    	public ExportDialog(JFrame parent) {
		super(parent, resources.getString("export.title"), true);
		
		GridBagConstraints gridBagConstraints;

        	exportPanel = new JPanel();
	        tempList = new JList(templates);
	        tempDescription = new JPanel();
	        descTextArea = new JTextArea();
	        tempAvail = new JLabel();
	        tempDesc = new JLabel();
	        buttons = new JPanel();
	        ok = new JButton();
	        cancel = new JButton();
		graphSizeButton = new JButton();
		scrollPane = new JScrollPane();
		
		setResizable(false);

		tempList.setCellRenderer(new IconRenderer());
		tempList.setSelectedIndex(0);
		loadTemplateDescriptions((Template) templates.getElementAt(0));
		
		descTextArea.setMargin(new Insets(5, 5, 5, 5));
		
		Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension ourDim = new Dimension();

		ourDim.height = (int) (screenDim.height * 0.4);
		ourDim.width = (int) (screenDim.width * 0.4);
		setSize(ourDim);
		
		screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((int) ((screenDim.width - getWidth()) / 2), (int) ((screenDim.height - getHeight()) / 2));

		screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((int) ((screenDim.width - getWidth()) / 2), (int) ((screenDim.height - getHeight()) / 2));
	       
		getContentPane().setLayout(new GridBagLayout());
	
	        addWindowListener(new WindowAdapter() {
	            public void windowClosing(WindowEvent evt) {
	                closeDialog(evt);
	            }
	        });
	
	        exportPanel.setLayout(new GridBagLayout());

        	exportPanel.setBorder(new TitledBorder(new EtchedBorder(), resources.getString("export.templates")));
	        tempList.setBorder(new LineBorder(new java.awt.Color(0, 0, 0)));
	        tempList.setFont(new Font("Dialog", 0, 12));
		tempList.setMinimumSize(new Dimension(100, 200));

		tempList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tempList.setVisibleRowCount(12);
		tempList.addListSelectionListener(this);
		
		scrollPane.getViewport().setView(tempList); 
		
		gridBagConstraints = new GridBagConstraints();
        	gridBagConstraints.gridx = 0;
        	gridBagConstraints.gridy = 1;
        	gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        	gridBagConstraints.insets = new Insets(7, 15, 20, 23);
        	exportPanel.add(scrollPane, gridBagConstraints);

        	tempDescription.setLayout(new BorderLayout());
		
        	tempDescription.setBorder(new LineBorder(new Color(0, 0, 0)));
		descTextArea.setColumns(20);
        	descTextArea.setEditable(false);
        	descTextArea.setTabSize(10);
		descTextArea.setLineWrap(true);
		descTextArea.setWrapStyleWord(true);
		
		tempDescription.add(descTextArea, BorderLayout.CENTER);

	        gridBagConstraints = new GridBagConstraints();
        	gridBagConstraints.gridx = 1;
	        gridBagConstraints.gridy = 1;
	        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
	        gridBagConstraints.insets = new Insets(7, 7, 20, 15);
	        exportPanel.add(tempDescription, gridBagConstraints);

	        tempAvail.setText(resources.getString("export.templates"));
	        gridBagConstraints = new GridBagConstraints();
	        gridBagConstraints.gridx = 0;
	        gridBagConstraints.gridy = 0;
	        gridBagConstraints.anchor = GridBagConstraints.WEST;
	        gridBagConstraints.insets = new Insets(32, 15, 0, 7);
	        exportPanel.add(tempAvail, gridBagConstraints);

	        tempDesc.setText(resources.getString("export.description"));
	        gridBagConstraints = new GridBagConstraints();
	        gridBagConstraints.gridx = 1;
	        gridBagConstraints.gridy = 0;
	        gridBagConstraints.anchor = GridBagConstraints.WEST;
		gridBagConstraints.insets = new Insets(32, 7, 0, 15);
	        exportPanel.add(tempDesc, gridBagConstraints);

        	gridBagConstraints = new GridBagConstraints();
	        gridBagConstraints.gridx = 0;
	        gridBagConstraints.gridy = 0;
	        gridBagConstraints.insets = new Insets(18, 18, 18, 18);
	        getContentPane().add(exportPanel, gridBagConstraints);

	        buttons.setLayout(new GridBagLayout());

	        cancel.setText(resources.getString("button.cancel"));
                cancel.addActionListener(new CancelListener());
		
		gridBagConstraints = new GridBagConstraints();
	        gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
	        gridBagConstraints.insets = new Insets(0, 0, 0, 10);
	        buttons.add(cancel, gridBagConstraints);

	        ok.setText(resources.getString("button.ok"));
		ok.addActionListener(new OKListener(this));

		gridBagConstraints = new GridBagConstraints();
	        gridBagConstraints.gridx = 3;
		gridBagConstraints.gridy = 0;
		buttons.add(ok, gridBagConstraints);

		graphSizeButton.setText(resources.getString("export.setgraph"));
		graphSizeButton.addActionListener(new SetGraphListener());
		
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.insets = new Insets(0, 0, 0, 22);
		buttons.add(graphSizeButton, gridBagConstraints);
		
	        gridBagConstraints = new GridBagConstraints();
	        gridBagConstraints.gridx = 0;
	        gridBagConstraints.gridy = 1;
	        gridBagConstraints.anchor = GridBagConstraints.EAST;
	        gridBagConstraints.insets = new Insets(0, 18, 15, 18);
	        getContentPane().add(buttons, gridBagConstraints);
	
	        pack();
		setSize(getPreferredSize());
		setResizable(false);
		
		setLocation((int) ((screenDim.width - getWidth()) / 2), (int) ((screenDim.height - getHeight()) / 2));
	}
	
	public void show() {
	        pack();
		super.show();
        }

	/** Close dialog */
	private void closeDialog(WindowEvent evt) {        
		setVisible(false);
		dispose();
	}

	/** @return	the <code>JList</code> with templates */ 
 	public JList getTemplateList() {
		return list;
	}

	/** @return 	selected <code>Template</code> from <code>JList</code> */
	public Template getSelectedTemplate() {
		int index = tempList.getSelectedIndex();
		return (Template) templates.getTemplateAt(index);
	}
	
	/** Loads template descriptions from template file */
	public void loadTemplateDescriptions(Template templ) {
		String tempDescr = templ.getDescription();
		
		descTextArea.setText("\n" + tempDescr + "\n\n" 
					+ resources.getString("export.author") +    ": " + templ.getAuthor() + "\n" 
					+ resources.getString("export.version") +   ": " + templ.getVersion() + "\n"
					+ resources.getString("export.extension") + ": " + templ.getExtension());
	}

	/** Format description of template
	 * @param desc	the <code>String</code> descibing template
	 * @return 	formated <code>String</code> for <code>JTextArea</code>
	 */
	public String formatDescriptor(String desc) {
		int columns = descTextArea.getColumns() + 10;
		int textLineWidth = 0;
		
		String formatedDesc = "";
		
		int lastAtWS = -1;
		int atWS = desc.indexOf(" ");
		
		if (atWS != -1) {
			String formatedLine = "";
			String substring;		
			
			do {
				atWS = desc.indexOf(" ", lastAtWS + 1);
					if (atWS != -1) {
						substring = desc.substring(lastAtWS + 1, atWS + 1);
					} else {
						substring = desc.substring(lastAtWS + 1 , desc.length());
					}
					
					if (substring.length() + formatedLine.length() <= columns) {
						formatedLine += substring; 

					} else {
						formatedDesc += " " + formatedLine + "  " + "\n";
						formatedLine = substring;
					}
				lastAtWS = atWS;
			} while (atWS != -1);
			
				formatedDesc += " " + formatedLine + " ";
			
			return formatedDesc;
		} else {
			return desc;
		}
		
	}

//----------------------------
//	   Listeners
//----------------------------
	
// ListSelectionListener
	public void valueChanged(ListSelectionEvent e) {
		
		Template exportTemplate = getSelectedTemplate();

		loadTemplateDescriptions(exportTemplate);
		
		String desc = exportTemplate.getDescription();
		String desc2 = exportTemplate.getExtension();
	}
// ...end

	protected class OKListener implements ActionListener {
	
		Component sourceComp;
	
		public OKListener(Component comp) {
			sourceComp = comp;
		}
		
		public void actionPerformed(ActionEvent e) {
			Template exportTemplate = getSelectedTemplate();
			
			exportTemplate.setImgExporter(ie);
			
			JFileChooser fc = new JFileChooser();
			fc.addChoosableFileFilter(new TemplateFileFilter(exportTemplate.getExtension()));

			int returnVal = fc.showDialog(sourceComp, resources.getString("button.save")); // <- Zeby tohle???

			if (returnVal != JFileChooser.APPROVE_OPTION) {
				return;
			}
			
			File file = fc.getSelectedFile();
			
			exportTemplate.exportTo(file);
	        	dispose(); 
		}
	}

        protected class CancelListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			dispose();
		}
	}

	protected class SetGraphListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			graphDialog.show();
		}
	}

	static {
                resources = ResourceBundle.getBundle("net.sf.vofce.gui.resources");
        }
 }

/** Filter for templates */
class TemplateFileFilter extends FileFilter {

        protected ResourceBundle resources;
	
	String extension;
	
	public TemplateFileFilter(String extension) {
	        resources = ResourceBundle.getBundle("net.sf.vofce.gui.resources");
		this.extension = "." + extension;
	}
	
	public boolean accept(File file) {
		
		return (file.isDirectory() || file.getPath().endsWith(extension));
	}

	public String getDescription() {
		return resources.getString("export.toformat") + " " + "(*" + extension + ")";
	}
}
